<?php

namespace App\Http\Middleware;
use App\Http\Controllers\UploadController;
use App\Http\Controllers\WxController;
use App\Models\User;
use App\Utils\CodeUtil;
use Closure;
class WxLogin {
	/**
	 * Handle an incoming request.
	 * 不分离的微信登陆
	 * @param  \Illuminate\Http\Request $request
	 * @param  \Closure $next
	 * @return mixed
	 */
	public function handle($request, Closure $next) {

		if (session('user')) {
            return $next($request);
        } else {
            // 微信登陆+注册
            $code = $request->input('code');
            if(empty($code)) {
                echo "<script>window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config("wechat.app_id")."&redirect_uri=http://".$request->getHost()."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'</script>";
                exit;
            }
            // 微信资料存储
            $wx = new WxController();
            $result = $wx->wxUserinfo();
            if($result["code"] == 500) {
                echo $result["msg"];
                exit;
            }
            $userinfo = (object)$result["data"];
            $user = User::where("openid",$userinfo->openid)->first();
            if(empty($user)) {
                $upload = new UploadController();
                $img = $upload->uploadMove($userinfo->headimgurl);
                // 注册
                $user = new User();
                $user->name = $userinfo->openid;
                $user->email = $userinfo->openid;
                $user->realname = $userinfo->nickname;
                $user->openid = $userinfo->openid;
                $user->thumb = $img["data"]["id"];
                $user->create();
            }
            $request->session()->put("user",$user);
            return $next($request);
        }
	}
}
